package com.newcapec.shiro.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.newcapec.shiro.constant.CommonConstant;
import com.newcapec.shiro.dao.RolesDao;
import com.newcapec.shiro.entity.Roles;
import com.newcapec.shiro.service.RolesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RolesServiceImpl implements RolesService {

    @Autowired
    private RolesDao rolesDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(Roles entity) {
        rolesDao.insert(entity);
        if(entity.getResourcesList() != null && entity.getResourcesList().size() > 0){
            rolesDao.insertResources(entity);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(Roles entity) {
        rolesDao.update(entity);
        if(entity.getResourcesList() != null){
            rolesDao.deleteResources(entity.getId());
            if(entity.getResourcesList().size() > 0){
                rolesDao.insertResources(entity);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void remove(Integer id) {
        rolesDao.delete(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeBatch(Integer[] id) {
        rolesDao.deleteBatch(id);
    }

    @Override
    public Roles findById(Integer id) {
        return rolesDao.selectById(id);
    }

    @Override
    public Map<String, Object> find(Integer pageNum, Integer pageSize, Roles entity) {
        PageHelper.startPage(pageNum, pageSize);
        List<Roles> list = rolesDao.select(entity);
        PageInfo<Roles> pageInfo = new PageInfo<>(list);
        long total = pageInfo.getTotal();
        Map<String, Object> map = new HashMap<>();
        map.put(CommonConstant.PAGE_LIST, list);
        map.put(CommonConstant.PAGE_TOTAL, total);
        return map;
    }

    @Override
    public List<Roles> findAll() {
        return rolesDao.selectAll();
    }

    @Override
    @Cacheable(value = "user:login:cache", key = "'role'+#userId", unless = "#result eq null")
    public List<Roles> findByUserId(Integer userId) {
        return rolesDao.selectByUserId(userId);
    }
}
